<?php

namespace app\system\controller\finance;

use app\common\controller\System;
use app\system\controller\goods\ZipArchive;
use ba\Filesystem;
use hehe\Numeral;
use hehe\Str;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;

/**
 * 商品管理
 */
class Account extends System {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = [];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\finance\Account;
    }


    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();


        $res = $this->model->where($where)->where(['filter_id' => $this->filter['id']])->order($order)->paginate($limit);
        $list = $res->items();



        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['filter_id'] = $this->filter['id'];
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function import() {
        $params = $this->request->post();
        // 读取xls文件内容
        $filePath = Filesystem::fsFit(public_path() . $params['url']);
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getSheet(0);
        $data = $sheet->toArray(); // 获取表格中的文字内容

        $file_type = '';
        $insert = [];
        foreach($data as $key => $val){
            if(!empty($val[0]) && strstr($val[0], '交易时间')) {
                $file_type = $val[1] == '取款额' ? '企业银行' : '建设银行';
                break;
            }else{
                unset($data[$key]);
            }
        }



        if($params['account_id'] == 2) { // 建设银行
            if($file_type != '建设银行') $this->error('请上传建设银行的收支明细');
            foreach($data as $key => $val){
                if(strstr($val[0], '交易时间')) continue;
                if(empty($val[0])) break;
                $insert[] = [
                    'trade_time' => strtotime($val[0]),
                    'other_side_name' => $val[5],
                    'other_side_account' => $val[6],
                    'income' => Numeral::restoreNumberFormat($val[2]) * 100,
                    'expenditure' => Numeral::restoreNumberFormat($val[1]) * 100,
                    'type' => $val[9],
                    'note' => $val[10],
                    'amount' => Numeral::restoreNumberFormat($val[3]) * 100,
                    'account_id' => $params['account_id'],
                    'create_time' => $this->timestamp,
                ];
            }
        }
        if($params['account_id'] == 3) { // 企业银行
            if($file_type != '企业银行') $this->error('请上传企业银行的收支明细');
            foreach($data as $key => $val){
                if(strstr($val[0], '交易时间')) continue;
                if(empty($val[0])) break;
                $trade_time = str_replace('.', '/', $val[0]);
                $insert[] = [
                    'trade_time' => strtotime($trade_time),
                    'other_side_name' => $val[6],
                    'income' => Numeral::restoreNumberFormat($val[2]) * 100,
                    'expenditure' => Numeral::restoreNumberFormat($val[1]) * 100,
                    'commission' => Numeral::restoreNumberFormat($val[5]) * 100,
                    'capital' => Numeral::restoreNumberFormat($val[4]) * 100,
                    'type' => $val[8],
                    'note' => $val[7],
                    'amount' => Numeral::restoreNumberFormat($val[3]) * 100,
                    'account_id' => $params['account_id'],
                    'create_time' => $this->timestamp
                ];
            }
        }

        if(empty($insert)){
            $this->error('未获取到文件中的数据');
        }

//        print_r($insert);

        $result = db::name('Finance_detail')->insertAll($insert);

        if($result){
            $this->success();
        }else{
            $this->error();
        }


        print_r($insert);
    }


    public function editDesc(){
        $params = $this->request->param();
        $update = [
            'desc' => empty($params['new_value']) ? null : $params['new_value'],
        ];
        db::name('finance_detail')->where(['id' => $params['id']])->update($update);
        $this->success();
    }

    public function uploadInvoice(){
        $params = $this->request->param();
        $attachment = db::name('attachment')->where('url', html_entity_decode($params['file']))->find();
        $invoice = [
            'id' => $attachment['id'],
            'url' => $attachment['url'],
            'name' => $attachment['name']
        ];
        $update = [
            'invoice' => json_encode($invoice)
        ];
        db::name('finance_detail')->where(['id' => $params['id']])->update($update);
        $this->success('', $invoice);
    }

    public function delInvoice(){
        $params = $this->request->param();
        db::name('finance_detail')->where(['id' => $params['id']])->update(['invoice' => null]);
        $this->success();
    }

    public function accountInfo(){
        $params = $this->request->param();
        $account = db::name('finance_account')->where(['id' => $params['id'], 'filter_id' => $this->filter['id']])->find();
        if($account){
            $this->success('', $account);
        }else{
            $this->success('', ['bank_name' => __('账户不存在')]);
        }

    }

}